package org.ala.tiktools.rpc.plugin.serializer;


import java.util.concurrent.ThreadPoolExecutor;
import java.util.function.Consumer;

import org.ala.tiktools.tools.thread_pool.ThreadPoolTools;

/**
 * 序列化反序列化线程池
 * <p>  把序列化/反序列化的任务从 EventLoop 线程中剥离出来
 * <p>  当没队列满时，主线程会阻塞
 *
 * @author ala
 * @date 2025-04-08 21:55
 */
public class SerializeThreadPool {
	
	
	/**
	 * 	序列化池子
	 */
	public static SerializeThreadPool INSTANCE;
	/**
	 * 	序列化工具
	 */
	public static ISerializer INSTANCE_SERIALIZER;
	
	
    /**
     * 	线程数
     */
    protected int coreSize;
    /**
     * 	任务队列数
     */
    protected int queueSize;
    /**
     * 	线程池
     */
    protected ThreadPoolExecutor pool;
    
    
    public static SerializeThreadPool build(int coreSize) {
    	SerializeThreadPool pool = new SerializeThreadPool();
    	if (coreSize > 0) {
    		pool.pool = ThreadPoolTools.build(coreSize, coreSize, 1024, "RpcSerializeThread");
    	}
    	return pool;
    }

    
    /**
     * 	序列化
     * 	<p>	默认用线程池，线程池满用主线程
     */
    public void serialize(Object o, Consumer<byte[]> consumer) {
    	if (pool == null) {
    		consumer.accept(INSTANCE_SERIALIZER.serialize(o));
    	} else {
    		try {
    			pool.execute(() -> consumer.accept(INSTANCE_SERIALIZER.serialize(o)));
    		} catch (Exception e) {
    			consumer.accept(INSTANCE_SERIALIZER.serialize(o));
    		}
    	}
    }
    /**
     * 	反序列化
     */
    public <T> void deSerlize(byte[] bytes, Class<T> clazz, Consumer<T> consumer) {
    	if (pool == null) {
    		consumer.accept(INSTANCE_SERIALIZER.deSerialize(bytes, clazz));
    	} else {
    		try {
    			pool.execute(() -> consumer.accept(INSTANCE_SERIALIZER.deSerialize(bytes, clazz)));
    		} catch (Exception e) {
    			consumer.accept(INSTANCE_SERIALIZER.deSerialize(bytes, clazz));
    		}
    	}
    }
    
}
